from flask import Flask, render_template
from flask_wtf.csrf import CSRFError

import os
import click

from app.panel import panel_bp
from app.software import soft_bp
from app.apis.v1 import api_v1

from app.models import Admin, Software, Command
from app.settings import config
from app.extensions import db, login_manager, csrf, migrate, avatars

basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))


def create_app(config_name=None):
    if config_name is None:
        config_name = os.getenv('FLASK_CONFIG', 'development')
    app = Flask('app')
    app.config.from_object(config[config_name])

    register_blueprints(app)
    register_extensions(app)
    register_errors(app)
    register_shell_context(app)
    register_template_context(app)
    register_commands(app)
    return app


def register_blueprints(app):
    app.register_blueprint(panel_bp)
    app.register_blueprint(soft_bp, url_prefix='/software')
    app.register_blueprint(api_v1, url_prefix='/api/v1')


def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    csrf.exempt(api_v1)
    migrate.init_app(app, db)


def register_shell_context(app):
    @app.shell_context_processor
    def make_shell_context():
        return dict(db=db, Admin=Admin, Software=Software)


def register_errors(app):
    @app.errorhandler(400)
    def bad_request(e):
        return render_template('errors/400.html'), 400

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def internal_server_error(e):
        return render_template('errors/500.html'), 500

    @app.errorhandler(CSRFError)
    def handle_csrf_error(e):
        return render_template('errors/400.html', description=e.description), 400


def register_template_context(app):
    @app.context_processor
    def make_template_context():
        return dict()


def register_commands(app):
    @app.cli.command()
    @click.option('--drop', is_flag=True, help='重建数据库')
    def initdb(drop):
        if drop:
            click.confirm('这个操作会删除你的数据库，确定吗？', abort=True)
            db.drop_all()
            click.echo('删除数据表')
        db.create_all()
        init_software()
        click.echo('初始化数据库')


def init_software():
    import json
    with open('app/panel/software.json', 'r') as f:
        softwareList = json.load(f)
    for each in softwareList:
        for item in softwareList.get(each):
            software = Software(name=item.get('name'), version=item.get('version'), slug=each,
                                describe=item.get('describe', 'A good software'))
            command = Command(install=item.get('cmd'), uninstall=item.get('uninstall'))
            software.cmd = command
            db.session.add(software)
            db.session.add(command)
            db.session.commit()
            print('{} has been added to database!'.format(software.name))
    print('All done.')
